package com.wandian.cqcsk.web;

import android.Manifest;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.widget.NestedScrollView;

import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.google.gson.JsonObject;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.view.CropImageView;
import com.mylib.libcore.AppContext;
import com.mylib.libcore.bean.BaseBean;
import com.mylib.libcore.config.RouterConfig;
import com.mylib.libcore.glide.GlideImageLoader;
import com.mylib.libcore.mvp.BaseActivity;
import com.mylib.libcore.network.rx.RxResultHelper;
import com.mylib.libcore.tools.CSJADTools;
import com.mylib.libcore.tools.GDTADTools;
import com.mylib.libcore.tools.TTAdManagerHolder;
import com.mylib.libcore.utils.ActivityUtil;
import com.mylib.libcore.utils.AppUtil;
import com.mylib.libcore.utils.FileUtil;
import com.mylib.libcore.utils.JsonUtil;
import com.mylib.libcore.utils.RetrofitUtil;
import com.mylib.libcore.utils.StatusBarUtilTools;
import com.mylib.libcore.utils.StrUtil;
import com.mylib.libcore.utils.ToastUtil;
import com.mylib.libcore.utils.UIUtils;
import com.mylib.libcore.utils.crc.AESUtils;
import com.mylib.widget.CircularProgressView;
import com.mylib.widget.CustomCoinToast;
import com.mylib.widget.ProgressWebView;
import com.tencent.smtt.export.external.interfaces.SslError;
import com.tencent.smtt.export.external.interfaces.SslErrorHandler;
import com.tencent.smtt.export.external.interfaces.WebResourceRequest;
import com.tencent.smtt.export.external.interfaces.WebResourceResponse;
import com.tencent.smtt.sdk.WebViewClient;
import com.wandian.cqcsk.R;
import com.tencent.smtt.export.external.interfaces.GeolocationPermissionsCallback;
import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebView;
import com.wandian.cqcsk.data.BaseAppApi;
import com.wandian.news.mvvm.toutiao.toutiaodetails.TouTiaoDetailActivity;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;
import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTRewardVideoAd;
import com.wandian.news.mvvm.toutiao.toutiaodetailsother.TouTiaoDetailOtherActivity;

import static com.mylib.libcore.config.AppConfig.CSJ_BANNER_ONE_ID;
import static com.mylib.libcore.config.AppConfig.CSJ_BANNER_TWO_ID;
import static com.mylib.libcore.config.AppConfig.CSJ_ZX_ID;
import static com.mylib.libcore.config.AppConfig.GDT_APP_MB_PIC_TWO;
import static com.mylib.libcore.config.NetConfig.BASE_SUCCESS_CODE;


@Route(path = RouterConfig.ROUTER_ACTIVITY_WEB)
public class WebActivity extends BaseActivity implements ProgressWebView.OnWebViewListener {

    private static final int REQUEST_CODE_PERMISSION_CHOOSE_PHOTO = 2002;
    private static final int REQUEST_CODE_CHOOSE_PHOTO = 2001;

    private ProgressWebView viewWeb;
    private ImageView iv_spz;
    private CircularProgressView circularProgressView;
    private NestedScrollView nestedScrollView;
    private RelativeLayout rl_top,rl_bottom;
    private FrameLayout fl_ad_bottom;
    private View activity_view;
    private ImageView iv_back;
    private TextView tv_title;
    private String url;
    private String title;
    private String type;
    private ValueCallback<Uri[]> fileChooserCallback;

    private int scrollNum = 0;//已加载进度
    private int scrollMaxNum = 3;//最大进度
    private int scrollStartY = 0;//动画开始进度
    private int scrollEndY = 0;//动画结束进度
    private boolean isMoving = false;//是否滚动
    private boolean isSubmitTask = false;//是否提交任务
    //看视频
    private TTRewardVideoAd mRewardVideoAd;
    private boolean videoPrepare = false;
    private TTAdNative mTTAdNative;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setContentView(R.layout.activity_web);
        circularProgressView = (CircularProgressView)findViewById(R.id.circularProgressView);
        iv_spz = (ImageView)findViewById(R.id.iv_spz);
        nestedScrollView = (NestedScrollView)findViewById(R.id.nestedScrollView);
        viewWeb = (ProgressWebView)findViewById(R.id.activity_view_web);
        //view_system = (View)findViewById(R.id.view_system);
        activity_view = (View)findViewById(R.id.activity_view);
        rl_top = (RelativeLayout)findViewById(R.id.rl_ad_top);
        rl_bottom = (RelativeLayout)findViewById(R.id.rl_ad_bottom);
        fl_ad_bottom = (FrameLayout)findViewById(R.id.fl_ad_bottom);
        iv_back = (ImageView) findViewById(R.id.tool_bar_iv_back);
        tv_title = (TextView) findViewById(R.id.tool_bar_tv_title);

        iv_back.setOnClickListener(v -> {
            finishhideSoftBoard();
            finish();});
        initView();
        initData();
        try {
            ActivityUtil.getInstance().finishActivity(TouTiaoDetailActivity.class);
        }catch (Exception e){}
        try {
            ActivityUtil.getInstance().finishActivity(TouTiaoDetailOtherActivity.class);
        }catch (Exception e){}

    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return 0;
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (viewWeb.canGoBack()) {
                viewWeb.goBack();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    private void initView() {
        StatusBarUtilTools.with(this,false)
                .setIsActionBar(false)
                .clearActionBarShadow()
                .setDrawable(getResources().getDrawable(R.drawable.sys_color))
                .init();
        activity_view.setVisibility(View.VISIBLE);
        showLoading(true);
        viewWeb.setWebChromeClient(new CWebChromeClient());
        viewWeb.setWebViewClient(new  CWebViewClient());
        viewWeb.setOnWebViewListener(this);
        viewWeb.addJavascriptInterface(new JSInterface(),"Android");
    }


    private void initData() {
        Bundle bundle =getIntent().getExtras();
        if(bundle != null){
            try {
                url = bundle.getString("url");
                title = bundle.getString("title");
                type = bundle.getString("type");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if(!UIUtils.isEmpty(title)) tv_title.setText(title);
        if(!UIUtils.isEmpty(type) && type.equals("微信头条")){
            initCSJAD();
            //看视频
            iv_spz.setOnClickListener(v -> {
                if(UIUtils.isOpenAD()) prepareVideo();//准备视频播放
            });
            if(AppContext.getInstance().getAppPreferencesHelper().getSubmitTaskNum()%5==4){
                circularProgressView.setVisibility(View.GONE);
                Glide.with(this).load(com.wandian.news.R.drawable.img_video_spz).into(iv_spz);
                iv_spz.setVisibility(View.VISIBLE);
            }else {
                circularProgressView.setVisibility(View.VISIBLE);
                iv_spz.setVisibility(View.GONE);
            }
            //获取广告
            rl_top.setVisibility(View.VISIBLE);
            rl_bottom.setVisibility(View.VISIBLE);
            CSJADTools.loadCSJAdMiddleBanner(getContext(),rl_top,"",CSJ_BANNER_ONE_ID,375,90);
            GDTADTools.loadHFAdByID(getContext(),fl_ad_bottom,GDT_APP_MB_PIC_TWO,375,0 );
            CSJADTools.loadCSJAdMiddleBanner(getContext(),rl_bottom,"",CSJ_BANNER_TWO_ID,375,120);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                nestedScrollView.setOnScrollChangeListener(new View.OnScrollChangeListener() {
                    @Override
                    public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                        if(Math.abs(scrollY-oldScrollY)>20){
                            if(!UIUtils.isEmpty(type) && type.equals("微信头条")){
                                if(!isMoving) setAnimation();
                            }
                        }
                    }
                });
            }else {
                circularProgressView.setVisibility(View.GONE);
            }
        }

        if(UIUtils.isEmpty(url)){
            return;
        }
        url = url.replace("&amp;","&");
        System.out.println("----pay>>>"+url);
        if (StrUtil.isUrl(url)){
            viewWeb.loadUrl(url);
        } else{
            viewWeb.loadDataWithBaseURL(null, getHtmlData(url), "text/html", "utf-8", null);
            System.out.println("----url>>>"+url);
            if (url.startsWith("weixin://wap/pay?") ||url.startsWith("weixin://scanQRCode")) {

                if (UIUtils.isWeixinAvilible(mContext)) {
                    Intent intent2 = new Intent();
                    intent2.setAction(Intent.ACTION_VIEW);
                    intent2.setData(Uri.parse(url));
                    startActivity(intent2);
                }
            }
            if(url.startsWith("alipayqr:") || url.startsWith("alipayqr")) {
                try {
                    startActivity(new Intent("android.intent.action.VIEW", Uri.parse(url)));
                } catch (Exception e) {
                    new AlertDialog.Builder(WebActivity.this)
                            .setMessage("未检测到支付宝客户端，请安装后重试。")
                            .setPositiveButton("立即安装", new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Uri alipayUrl = Uri.parse("https://d.alipay.com");
                                    startActivity(new Intent("android.intent.action.VIEW", alipayUrl));
                                }
                            }).setNegativeButton("取消", null).show();
                }
            }
        }
    }

    /**
     * 初始化穿山甲广告
     */
    private void initCSJAD(){
        try{
            TTAdManagerHolder.init(WebActivity.this);
            mTTAdNative.loadRewardVideoAd(CSJADTools.getAdSlot("浏览奖励",1,"news"),
                    new TTAdNative.RewardVideoAdListener() {
                        @Override
                        public void onError(int i, String s) {
                            videoPrepare = false;
                        }

                        @Override
                        public void onRewardVideoAdLoad(TTRewardVideoAd ttRewardVideoAd) {
                            videoPrepare = false;
                            if(UIUtils.isEmpty(ttRewardVideoAd))return;
                            mRewardVideoAd = ttRewardVideoAd;
                        }

                        @Override
                        public void onRewardVideoCached() {
                            videoPrepare = true;
                        }
                    });
        }catch (Exception e){

        }
    }

    /**
     * 准备视频
     */
    private void prepareVideo(){
        if (mRewardVideoAd != null && videoPrepare) {
            mRewardVideoAd.setRewardAdInteractionListener(new TTRewardVideoAd.RewardAdInteractionListener() {

                @Override
                public void onAdShow() {
                    Log.d("VideoAd","onAdShow");
                    //   Toast.makeText(RewardVideoActivity.this, "rewardVideoAd show", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onAdVideoBarClick() {
                    Log.d("VideoAd","onAdVideoBarClick");
                    //  Toast.makeText(RewardVideoActivity.this, "rewardVideoAd bar click", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onAdClose() {
                    Log.d("VideoAd","onAdClose");
                    //   Toast.makeText(RewardVideoActivity.this, "rewardVideoAd close", Toast.LENGTH_SHORT).show();
                    mRewardVideoAd = null;
                    CustomCoinToast.showToast(WebActivity.this,"视频奖励","1金币");
                }

                @Override
                public void onVideoComplete() {
                    Log.d("VideoAd","onVideoComplete");
                    // Toast.makeText(RewardVideoActivity.this, "rewardVideoAd complete", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onVideoError() {
                    Log.d("VideoAd","onVideoError");
                }

                @Override
                public void onRewardVerify(boolean b, int i, String s, int i1, String s1) {

                }



                @Override
                public void onSkippedVideo() {
                    Log.d("VideoAd","onSkippedVideo");
                }
            });
            //展示广告，并传入广告展示的场景
            mRewardVideoAd.showRewardVideoAd(WebActivity.this, TTAdConstant.RitScenes.CUSTOMIZE_SCENES, "scenes_test");
        } else {
            ToastUtil.show("视频资源准备中，请稍后再试");
        }
    }

    //任务动画
    private void setAnimation() {
        isMoving =true;
        scrollNum++;
        if(scrollNum<scrollMaxNum){
            if(scrollNum ==0 && scrollEndY==0){
                scrollStartY = 0;
                scrollEndY = 100/scrollMaxNum;
            }else{
                scrollStartY = scrollEndY;
                scrollEndY = (100/scrollMaxNum ) * scrollNum;
            }
        }else{
            scrollStartY = scrollEndY;
            scrollEndY = 100;
        }
        if(scrollStartY ==100){
            submitTask();
        }else{
            ValueAnimator animator =  ValueAnimator.ofInt(scrollStartY, scrollEndY).setDuration(2500);
            animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    if (animation != null) {
                        int currentValue = (int) animation.getAnimatedValue();
                        Log.d("setAnimation",currentValue+"==="+scrollEndY+"==="+scrollStartY);
                        circularProgressView.setProgress(currentValue);
                        if(currentValue >=scrollEndY) isMoving = false;
                        if(currentValue>=100) submitTask();
                    }
                }
            });
            animator.start();
        }
    }


    /**
     * 提交任务
     */
    private void submitTask(){
        if(!isSubmitTask){
            isSubmitTask = true;
            readMoney(this);
        }
    }
    /**
     * 阅读奖励
     */
    public void readMoney(Context context){
        BaseAppApi  baseAppApi = RetrofitUtil.getAppRetrofit().create(BaseAppApi.class);
        JsonObject jsonObject = new JsonObject();
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("advertName", "阅读奖励");
        hashMap.put("sourceType", "read");
        hashMap.put("remark", "");
        jsonObject.addProperty("wdk", AESUtils.getInstance().encrypt(hashMap));
        RxResultHelper.getHttpObservable(context, baseAppApi.readMoney(jsonObject))
                .subscribe(new Observer<BaseBean<Object>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }
                    @Override
                    public void onNext(BaseBean<Object> bean) {
                        Log.d("upFightNum",   JsonUtil.toJson(bean));
                        if(!UIUtils.isEmpty(bean) && bean.getCode()==BASE_SUCCESS_CODE){
                            if(!UIUtils.isEmpty(bean.getMsg()) && bean.getMsg().equals("今日金币奖励已上限")){
                                ToastUtil.show("今日金币奖励已上限");
                            }else {
                                int num = AppContext.getInstance().getAppPreferencesHelper().getSubmitTaskNum();
                                AppContext.getInstance().getAppPreferencesHelper().setSubmitTaskNum(num+1);
                                CustomCoinToast.showToast(context,"阅读奖励","0.2金币");
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private final class JSInterface{

        @JavascriptInterface
        public void goBack(){
            Log.d("nativeBack","nativeBack");
            if (viewWeb.canGoBack()) {
                viewWeb.goBack();
            }else {
                finish();
            }
        }

        @JavascriptInterface
        public void nativeBackToRoot() {
            ActivityUtil.getInstance().backToHome();
        }


    }



    private String getHtmlData(String bodyHTML) {
        String head = "<head>" +
                "   <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0\"/>" +
                "   <style> " +
                "       *{font-size: 14px; color: #404040;} " +
                "       img{max-width: 100%; width:auto; height: auto;}" +
                "   </style>" +
                "</head>";
        return "<html>" + head + "<body>" + bodyHTML + "</body></html>";
    }

    @Override
    public void onTitleChanged(String title) {

    }

    @Override
    public void onFileChooser(ValueCallback<Uri[]> valueCallback, WebChromeClient.FileChooserParams fileChooserParams) {
        if (fileChooserCallback != null) {
            fileChooserCallback.onReceiveValue(null);
        }
        this.fileChooserCallback = valueCallback;
        choosePhoto();
    }

    @Override
    public void interceptUrl(String url) {
        if(UIUtils.isEmpty(url)){
            return;
        }

    }

    @AfterPermissionGranted(REQUEST_CODE_PERMISSION_CHOOSE_PHOTO)
    public void choosePhoto() {
        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (EasyPermissions.hasPermissions(this, perms)) {
            openPhotoChooseUI();
        } else {
            EasyPermissions.requestPermissions(this, "请开起存储空间权限，以正常使用应用", REQUEST_CODE_PERMISSION_CHOOSE_PHOTO, perms);
        }
    }


    /**
     * WebViewClient
     */
    public class CWebViewClient extends WebViewClient {

        @Override
        public boolean shouldOverrideUrlLoading(WebView webView, WebResourceRequest webResourceRequest) {
            Log.d("webResourceRequest", webResourceRequest.getUrl()+"==");
            if(webResourceRequest.getUrl() != null){
                String urlString = webResourceRequest.getUrl().toString();
                if (urlString.startsWith("weixin://wap/pay?")  || urlString.startsWith("wechat")) {
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse(urlString));
                    startActivity(intent);
                    return true;
                }
                if(urlString.startsWith("alipays:") || urlString.startsWith("alipay") || urlString.startsWith("alipayqr")) {
                    try {
                        startActivity(new Intent("android.intent.action.VIEW", Uri.parse(urlString)));
                    } catch (Exception e) {
                        new AlertDialog.Builder(WebActivity.this)
                                .setMessage("未检测到支付宝客户端，请安装后重试。")
                                .setPositiveButton("立即安装", new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        Uri alipayUrl = Uri.parse("https://d.alipay.com");
                                        startActivity(new Intent("android.intent.action.VIEW", alipayUrl));
                                    }
                                }).setNegativeButton("取消", null).show();
                    }
                    return true;
                }
            }
            return super.shouldOverrideUrlLoading(webView, webResourceRequest);
        }



        @Override
        public WebResourceResponse shouldInterceptRequest(WebView webView, WebResourceRequest webResourceRequest) {
            return super.shouldInterceptRequest(webView, webResourceRequest);
        }

        @Override
        public WebResourceResponse shouldInterceptRequest(WebView webView, WebResourceRequest webResourceRequest, Bundle bundle) {
            return super.shouldInterceptRequest(webView, webResourceRequest, bundle);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return false;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);

        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
//            String jsString = "javascript:if (SDW_WEB.onAndriod) {\n" +
//                    "    window.sdwMsg = {\n" +
//                    "        share: function(shareInfo) {\n" +
//                    "            shandwShare(shareInfo);\n" +
//                    "        }\n" +
//                    "    }\n" +
//                    "}\n" +
//                    "\n" +
//                    "function shandwShare(shareInfo) {\n" +
//                    "    console.log(shareInfo);\n" +
//                    "}\n" +
//                    "\n" +
//                    "// 成功调用\n" +
//                    "function shandwShareSuccess() {\n" +
//                    "    if (shandwshare && shandwshare.success) {\n" +
//                    "        shandwshare.success();\n" +
//                    "    }\n" +
//                    "}\n" +
//                    "\n" +
//                    "function shandwShareCancel() {\n" +
//                    "    if (shandwshare && shandwshare.cancel) {\n" +
//                    "        shandwshare.cancel();\n" +
//                    "    }\n" +
//                    "}";
//            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
//                viewWeb.evaluateJavascript(jsString, null);
//            } else {
//                viewWeb.loadUrl(jsString);
//            }
        }


        @Override
        public void onReceivedSslError(WebView webView, SslErrorHandler handler, SslError error) {
            // 接受所有网站的证书，忽略SSL错误，执行访问网页--google ssl 错误
            handler.proceed();
//            sslErrorHandler.cancel(); // Android默认的处理方式-不接受
//            handler.proceed();// 接受所有网站的证书
            super.onReceivedSslError(webView, handler, error);
        }


    }

    /**
     * 自定义ChromeClient类，处理加载进度条、文件选择、标题等内容
     */
    public class CWebChromeClient extends WebChromeClient {

        @SuppressLint("CheckResult")
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            Observable.just(newProgress)
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Consumer<Integer>() {
                        @Override
                        public void accept(Integer i) {
                            if (i == 100) {
                                hideLoading();
                                activity_view.setVisibility(View.GONE);
                            }
                        }
                    });

            super.onProgressChanged(view, newProgress);
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
        }

        @Override
        public void onGeolocationPermissionsShowPrompt(String s, GeolocationPermissionsCallback geolocationPermissionsCallback) {
            geolocationPermissionsCallback.invoke(s, true, true);
            super.onGeolocationPermissionsShowPrompt(s, geolocationPermissionsCallback);
        }

        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> valueCallback, FileChooserParams fileChooserParams) {
            return super.onShowFileChooser(webView, valueCallback, fileChooserParams);
        }


    }


    private void openPhotoChooseUI() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器
        imagePicker.setMultiMode(false);  //显示拍照按钮
        imagePicker.setShowCamera(true);  //显示拍照按钮
        imagePicker.setCrop(false);        //允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(true); //是否按矩形区域保存
        imagePicker.setSelectLimit(1);    //选中数量限制
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
        imagePicker.setFocusWidth(800);   //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(800);  //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(300);//保存文件的宽度。单位像素
        imagePicker.setOutPutY(300);//保存文件的高度。单位像素

        Intent intent = new Intent(this, ImageGridActivity.class);
        startActivityForResult(intent, REQUEST_CODE_CHOOSE_PHOTO);
    }

    @Override
    public void showLoading(boolean isDialog) {
        super.showLoading(isDialog);
    }

    @Override
    public void hideLoading() {
        super.hideLoading();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (fileChooserCallback == null) {
            return;
        }
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == REQUEST_CODE_CHOOSE_PHOTO) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (images != null && images.size() > 0) {
                    Uri uri = FileUtil.getUri(getContext(), new File(images.get(0).path));
                    fileChooserCallback.onReceiveValue(new Uri[]{uri});
                    fileChooserCallback = null;
                    return;
                }
            }
        }
        if (fileChooserCallback != null) {
            fileChooserCallback.onReceiveValue(null);
            fileChooserCallback = null;
        }
    }
}
